<?php
namespace Home\Controller;

class LoginController extends \Think\Controller
{
    // 登录页面
    public function index()
    {
        $this->display();
    }

    // 接收登录表单
    public function doLogin()
    {
        $userInfo = M('member')
        ->where([
            'name' => I('post.name'),
            'passwd' => I('post.passwd')
        ])
        ->find();

        if($userInfo == false) {
            $this->error('用户名或密码错误');
        } else {
            session('userInfo', $userInfo);
            $this->success('登录成功', U('Index/index'));
        }
    }

    // 注册页面
    public function register()
    {
        $this->display();
    }

    // 接收注册表单
    public function doRegister()
    {
        $model = D('member');
        $res = $model->create();

        if($res === false) {
            $this->error($model->getError());
        } else {
            $uid = $model->add();
            if($uid === false) {
                $this->error('用户注册失败');
            } else {
                $this->success('注册成功，请登录。', U('Index/Index'));
            }
        }
    }

    public function logout()
    {
        session('userInfo', null);
        $this->success('退出成功', U('Index/index'));
    }
}